package com.wnxy.portal.controller;

import cn.hutool.jwt.JWTUtil;
import com.google.code.kaptcha.Constants;
import com.wnxy.portal.common.constant.RedisConstant;
import com.wnxy.portal.common.result.impl.BusinessCodeEnum;
import com.wnxy.portal.common.result.Result;
import com.wnxy.portal.common.exception.Asserts;
import com.wnxy.portal.common.util.TokenUtil;
import com.wnxy.portal.entity.User;
import com.wnxy.portal.model.dto.RegisterDTO;
import com.wnxy.portal.model.dto.UserDto;
import com.wnxy.portal.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpSession;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Jet
 * @since 2023-12-11
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TokenUtil tokenUtil;

    /**
     * 登录方法
     * 返回状态码：
     * 50001    验证码为空
     * 50002    验证码错误
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserDto userDto, HttpSession session){
        log.debug("请求参数：{}",userDto);

        // 校验验证码是否为空
        Asserts.error(StringUtils.isEmpty(userDto.getValidateCode()),BusinessCodeEnum.VERRIFY_CODE_IS_NULL);

        // 校验验证码: session中存储的验证码与请求参数中验证码对比
        Asserts.error(
                !session.getAttribute(Constants.KAPTCHA_SESSION_KEY).equals(userDto.getValidateCode()),
                BusinessCodeEnum.VERRIFY_CODE_ERROR);

        // 校验账号密码是否正确
        User user = userService.login(userDto.getName(),userDto.getPassword());
        Asserts.error(Objects.isNull(user),BusinessCodeEnum.LOGIN_FAILED);

        // 登录成功, 生成token
        String token = tokenUtil.createToken(user.getId(),user.getNickname());

        // 放入redis
        redisTemplate.opsForValue().set(
                RedisConstant.USER_TOKEN_PREFIX+user.getId(),token, Duration.ofMinutes(300));
        // 返回token
        return Result.ok(token);
    }

    /**
     * 获取登录用户
     * @return
     */
    @GetMapping("/getLoginName")
    public Result getLoginName(@RequestHeader("Authorization") String token){
        token = token.replace("Bearer ", "");
        String nickName = (String) JWTUtil.parseToken(token).getPayload("nickName");
        return Result.ok(nickName);
    }
    /**
     * 注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody RegisterDTO registerDTO){
        userService.register(registerDTO);
        return Result.ok();
    }
}
